using System;
using Game.Core;
using Game.Core.Loader;
using Game.Main.Event;
using Game.Manager;
using UnityEngine;

namespace Game.Main.View
{
	public class BaseView : EventObject
	{
		public GameObject prefab;

		public Transform transform;

		public bool isHideScene;

		protected Transform parent;

		protected string prefabPath;

		protected string viewName;

		protected bool isLoad;

		protected bool isInitComplete;

		public bool IsOpen
		{
			get
			{
				return prefab != null && prefab.activeSelf;
			}
		}

		public bool IsInitComplete
		{
			get
			{
				return prefab != null && isInitComplete;
			}
		}

		public BaseView(string prefabPath)
			: this(prefabPath, Singleton<UIManager>.Instance.uiLayer)
		{
		}

		public BaseView(string prefabPath, Transform parent)
		{
			this.prefabPath = prefabPath;
			this.parent = parent;
		}

		public virtual void Open()
		{
			if (prefab == null)
			{
				if (!isLoad)
				{
					isLoad = true;
					Load();
				}
			}
			else
			{
				ActiveView();
				Fire(new BaseEvent(ViewEvent.VIEW_OPEN));
			}
		}

		public virtual void Close(bool isDestroy = false)
		{
			if (IsOpen || isDestroy)
			{
				if (isDestroy)
				{
					Singleton<UIManager>.Instance.RemoveView(this);
					UnityEngine.Object.Destroy(prefab);
					prefab = null;
					Singleton<AssetBundleManager>.Instance.UnloadUnusedAssets();
				}
				else
				{
					prefab.SetActive(false);
				}
				Singleton<UIManager>.Instance.CloseView(this);
			}
		}

		public override void Destroy()
		{
			base.Destroy();
			Close(true);
		}

		public virtual void Load()
		{
			ResourceLoader resourceLoader = new ResourceLoader(prefabPath, viewName);
			resourceLoader.Bind(LoadEvent.LOAD_COMPLETE, OnLoadComplete);
			resourceLoader.Load();
		}

		private void OnLoadComplete(BaseEvent evt)
		{
			ResourceLoader resourceLoader = (ResourceLoader)evt.sender;
			if (parent != null)
			{
				prefab = UnityEngine.Object.Instantiate((GameObject)resourceLoader.resource);
				transform = prefab.transform;
				transform.SetParent(parent, false);
				transform.name = viewName;
				ActiveView();
				OnLoaded();
				isInitComplete = true;
				Fire(new BaseEvent(ViewEvent.VIEW_OPEN));
			}
			resourceLoader.Destroy();
		}

		protected virtual void ActiveView()
		{
			prefab.SetActive(true);
			Singleton<UIManager>.Instance.AddView(this);
		}

		protected virtual void OnLoaded()
		{
		}

		public Transform GetChild(string name)
		{
			try
			{
				return transform.Find(name);
			}
			catch (Exception ex)
			{
				Trace.Log(ex.Message);
				return null;
			}
		}
	}
}
